package com.alma.talk;

import java.util.Properties;

import javax.swing.SwingUtilities;

import org.omg.CORBA.ORB;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.PortableServer.POAManager;
import org.omg.PortableServer.POAManagerPackage.AdapterInactive;

import com.alma.MTalk.Peer;
import com.alma.MTalk.PeerPOATie;
import com.alma.naming.EasyNaming;
import com.alma.talk.ui.TalkWindow;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		SwingUtilities.invokeLater(new Runnable(){
			public void run(){
				TalkWindow window = new TalkWindow("Talk To Much"
													,700
													,450
				);
				window.setAll();
				window.showAll();
			}
		});
		
//		System.exit(0);
        
        try {

        	Properties props = new Properties();
            props.put("org.omg.CORBA.ORBInitialPort", "1050");
            props.put("org.omg.CORBA.ORBInitialHost", "127.0.0.1");
    	
        	final ORB orb = ORB.init(args, props);        	
        	String pseudo = "toto";

        	// On enregistre l'utilisateur  
        	// Deploiement du RootPOA
        	org.omg.CORBA.Object obj = orb.resolve_initial_references("RootPOA");
        	POA rootPOA = POAHelper.narrow(obj);
        	final POAManager manager = rootPOA.the_POAManager();


        	// On recupere l'ior du  naming service et on initialise son interface
//        	String fichier = "iorNamingService.ref";
//        	BufferedReader inFromUserFile;
//
//        	inFromUserFile = new BufferedReader(new InputStreamReader(new FileInputStream(fichier)));
//        	String  ior = inFromUserFile.readLine();


        	// On met le orb.run() dans un thread, car il est bloquant 
        	Runnable r=new Runnable()
        	{
        		public void run()
        		{
        			try {
        				manager.activate();
        			} catch (AdapterInactive e) {
        				e.printStackTrace();
        			}
        			orb.run();       
        		}
        	};

        	Thread runOrb=new Thread(r);
        	runOrb.start();

        	EasyNaming naming = new EasyNaming(orb);
        	TalkImpl talk = new TalkImpl(orb);
        	
        	// Creation du peer local
        	PeerImpl peerImpl = new PeerImpl(orb, talk, pseudo, new PeerListener() {				
				@Override
				public boolean onTalkRequest(PeerImpl peer, String subject, String info) {
					return true;
				}
			});
        	PeerPOATie convTie = new PeerPOATie(peerImpl);
        	Peer peerLocal = convTie._this(orb);

        	// On enregistre le client
        	naming.rebind_from_string("/talk/" + pseudo, peerLocal);

        	// On desinscrit l'utilisateur
        	naming.unbind_from_string("/talk/" + pseudo); 

        	// On arrete le thread runOrb
        	runOrb.interrupt();

        } catch (Exception e1) {
                e1.printStackTrace();
        }
    
	}

}
